package com.jeequan.jeepay.mch.service.impl;

import com.jeequan.jeepay.core.constants.BalanceSourceTypeEnum;
import com.jeequan.jeepay.core.entity.Balance;
import com.jeequan.jeepay.core.entity.PaymentOrder;
import com.jeequan.jeepay.core.entity.PaymentUsdtOrder;
import com.jeequan.jeepay.core.entity.vo.CreateUsdtOrderVO;
import com.jeequan.jeepay.core.model.security.JeeUserDetails;
import com.jeequan.jeepay.mch.service.PaymentService;
import com.jeequan.jeepay.service.BalanceService;
import com.jeequan.jeepay.service.PaymentOrderService;
import com.jeequan.jeepay.service.PaymentUsdtOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 代付服务实现类
 * @author : wondream322@gmail.com
 * @date : 2023-8-19
 */
@Service
public class PaymentServiceImpl implements PaymentService {

    @Autowired
    BalanceService balanceService;

    @Autowired
    PaymentOrderService paymentOrderService;

    @Autowired
    PaymentUsdtOrderService paymentUsdtOrderService;

    @Transactional
    @Override
    public PaymentOrder createOrder(PaymentOrder orderVO) {
        // 1.添加代付订单
        PaymentOrder result = paymentOrderService.insert(orderVO);
        if (result==null) {
            return null;
        }
        // 2.获取当前用户信息
        JeeUserDetails jeeUserDetails = JeeUserDetails.getCurrentUserDetails();
        int memberId = jeeUserDetails.getSysUser().getId().intValue();
        // 3.减少余额
        balanceService.deductBalance(memberId, orderVO.getBalanceType(), orderVO.getBalanceLevel(), orderVO.getWithdrawAmount(), BalanceSourceTypeEnum.PAYMENT.getSourceType(), result.getId());
        return result;
    }

    @Override
    public PaymentUsdtOrder createUsdtOrder(CreateUsdtOrderVO createUsdtOrderVO) {
        // 1.获取当前用户信息
        JeeUserDetails jeeUserDetails = JeeUserDetails.getCurrentUserDetails();
        int memberId = jeeUserDetails.getSysUser().getId().intValue();
        // 2.获取钱包
        Balance balanceDO = balanceService.queryById(createUsdtOrderVO.getBalanceId());
        // 3.组装usdt订单对象
        PaymentUsdtOrder paymentUsdtOrder = new PaymentUsdtOrder();
        paymentUsdtOrder.setAmount(createUsdtOrderVO.getAmount());
        paymentUsdtOrder.setMemberId(memberId);
        paymentUsdtOrder.setUsdtAddress(createUsdtOrderVO.getUsdtAddress());
        // 4.添加代付订单
        PaymentUsdtOrder result = paymentUsdtOrderService.insert(paymentUsdtOrder);
        if (result==null) {
            return null;
        }
        // 3.减少余额
        balanceService.deductBalance(memberId, balanceDO.getBalanceType(), balanceDO.getBalanceLevel(), createUsdtOrderVO.getAmount(), BalanceSourceTypeEnum.PAYMENT.getSourceType(), result.getId());
        return result;
    }
}
